/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package isvp.events;

import isvp.constants.UIConstants;
import isvp.interfaces.Application;
import isvp.interfaces.ISVPFrame;
import isvp.interfaces.Privilege;
import isvp.tree.customizations.ISVPTreeNode;
import isvp.ui.beans.ISVPJPanel;
import isvp.ui.beans.ISVPTree;
import java.awt.CardLayout;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author jjophin
 */
public class ISVPTreeSelectionEvent implements TreeSelectionListener {
    private ISVPFrame frame;
    private ISVPTree componentTree;
    private CardLayout treeCards;
    
    public ISVPTreeSelectionEvent (ISVPFrame frame, ISVPTree tree) {
        this.frame = frame;
        componentTree = tree;
        componentTree.addTreeSelectionListener(this);
        treeCards = (CardLayout)frame.getPanelLayout();
    }
    
    @Override
    public void valueChanged(TreeSelectionEvent e) {
        ISVPTreeNode selectedNode = (ISVPTreeNode)componentTree.getLastSelectedPathComponent();
        TreePath currentSelectedPath = componentTree.getSelectionPath();
        if(selectedNode == null)
            return;
        
        //Setting the panel on the top
        ///ISVPJPanel selectedPanel = (ISVPJPanel)selectedNode.getUserObject();
        //selectedPanel.setOnTop();

        //Calling the method to set the data
        if(selectedNode.getName().equals(UIConstants.ISVP_NODE_NAME)) {
            treeCards.show(frame.getContainerPane(), selectedNode.getName());
        } else if(selectedNode.isLeaf()) {
            String parentNodeName = selectedNode.getParentNodeName();
            Object dataObject = selectedNode.getDataObject();
            if(parentNodeName.equals(UIConstants.APPLICATION_NODE_NAME)) {
                frame.fillApplicationDetails((Application)dataObject);                
            } else if(parentNodeName.equals(UIConstants.PRIVILEGES_NODE_NAME)) {
                frame.fillPrivilegeDetails((Privilege)dataObject);
            }
            treeCards.show(frame.getContainerPane(), parentNodeName);
        } else if (selectedNode.isComponentNode() && !componentTree.isExpanded(currentSelectedPath)) {
            TreeNode firstChild = selectedNode.getFirstChild();
            TreePath firstChildPath = currentSelectedPath.pathByAddingChild(firstChild);
            componentTree.setSelectionPath(firstChildPath);
        }           
    }
    
}
